package com.jinzhi.jzweb.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.type.EnumErrorCode;
import com.jinzhi.common.utils.EhCacheUtil;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.pojo.ChapterItemBankVo;
import com.jinzhi.jzweb.pojo.ErroeDownVo;
import com.jinzhi.jzweb.pojo.ErrorCodeVo;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.jzweb.utils.EasyPoiUtil;
import com.jinzhi.jzweb.utils.IdCardUtil;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.*;

/**
 * <pre>
 * 章节题库表
 * </pre>
 * <small> 2020-02-24 21:00:11 | lance</small>
 */
@Slf4j
@Controller
@RequestMapping("/jzweb/chapterItemBank")
public class ChapterItemBankController extends BaseController {
    @Autowired
    private ChapterItemBankService chapterItemBankService;
    @Autowired
    private UserService userService;
    @Autowired
    private ChapterService chapterService;
    @Autowired
    private CoursesService coursesService;
    @Autowired
    private KnowledgePointsService knowledgePointsService;
    @Autowired
    private ItemBankService itemBankService;
    @Autowired
    private TrainingPapersService trainingPapersService;
    @Autowired
    private TrainingQuestionsService trainingQuestionsService;

    @GetMapping()
    @RequiresPermissions("jzweb:chapterItemBank:chapterItemBank")
    String ChapterItemBank(Model model) {
        List<Map> maps;
        //根据当前登录人的机构id，查询到对应机构的课程；如是超级管理员，则不需要机构查询
        String roleName = getRoleNames();
        if (!roleName.contains("超级用户角色")) {
            Map map = new HashMap();
            map.put("orgId", this.getUser().getOrgId());
            //讲师
            if(roleName.contains("讲师") && !roleName.contains("培训机构")){
                map.put("userId",this.getUserId());
            }
            maps = coursesService.selCourseList(map);
        } else {
            maps = coursesService.selAllCourseList();
        }
        model.addAttribute("courses", maps);
        return "jzweb/chapterItemBank/chapterItemBank";
    }

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("jzweb:chapterItemBank:chapterItemBank")
    public Result<Page<ChapterItemBankDO>> list(HttpServletRequest req, ChapterItemBankDO chapterItemBankDTO) {
        Wrapper<ChapterItemBankDO> wrapper = new EntityWrapper<ChapterItemBankDO>().orderBy("id", false);
        if (chapterItemBankDTO.getState() != null) {
            wrapper.eq("state", chapterItemBankDTO.getState());
        }
        if (chapterItemBankDTO.getTopicTypes() != null) {
            wrapper.eq("topic_types", chapterItemBankDTO.getTopicTypes());
        }
        if (chapterItemBankDTO.getContents() != null) {
            wrapper.like("contents", chapterItemBankDTO.getContents());
        }

        String strr = roleCourse(req,chapterItemBankDTO.getCoursesName());
        if (org.apache.commons.lang.StringUtils.isBlank(strr)) {
            wrapper.and();
            wrapper.eq("courses_id", null);
        } else if(!strr.equals("@#$%^&*!~")){
            wrapper.and();
            wrapper.in("courses_id", strr.substring(0, strr.length() - 1));
        }

        if (StringUtils.isNotBlank(chapterItemBankDTO.getChapterName())) {
            Wrapper<ChapterDO> orWrapper = new EntityWrapper<ChapterDO>().like("name", chapterItemBankDTO.getChapterName());
            List<ChapterDO> chapterDOS = chapterService.selectList(orWrapper);
            String str = "";
            for (ChapterDO chapterDO : chapterDOS) {
                str = str + chapterDO.getId() + ",";
            }
            wrapper.and();
            if (org.apache.commons.lang3.StringUtils.isNotBlank(str)) {
                wrapper.in("chapter_id", str.substring(0, str.length() - 1));
            } else {
                wrapper.eq("chapter_id", null);
            }
        }

        Page<ChapterItemBankDO> page = chapterItemBankService.selectPage(getPage(ChapterItemBankDO.class), wrapper);
        List list = new ArrayList();
        for (int i = 0; i < page.getRecords().size(); i++) {
            ChapterItemBankDO obj = (ChapterItemBankDO) page.getRecords().get(i);
            if (obj.getCoursesId() != null) {
                CoursesDO coursesDO = coursesService.selectById(obj.getCoursesId());
                if (coursesDO != null) {
                    obj.setCoursesName(coursesDO.getName());
                }
            }
            if (obj.getChapterId() != null) {
                ChapterDO chapterDO = chapterService.selectById(obj.getChapterId());
                if (chapterDO != null) {
                    obj.setChapterName(chapterDO.getName());
                }
            }
            if (obj.getCreaterId() != null) {
                UserDO userDO = userService.selectById(obj.getCreaterId());
                if (userDO != null) {
                    obj.setCreaterName(userDO.getUsername());
                }
            }
            if (obj.getUpdaterId() != null) {
                UserDO userDO = userService.selectById(obj.getUpdaterId());
                if (userDO != null) {
                    obj.setUpdaterName(userDO.getUsername());
                }
            }
            list.add(obj);
        }
        page.setRecords(list);
        return Result.ok(page);
    }

    @GetMapping("/add")
    @RequiresPermissions("jzweb:chapterItemBank:add")
    String add(Model model) {
        List<Map> maps;
        //根据当前登录人的机构id，查询到对应机构的课程；如是超级管理员，则不需要机构查询
        String roleName = getRoleNames();
        if (!roleName.contains("超级用户角色")) {
            Map map = new HashMap();
            map.put("orgId", this.getUser().getOrgId());
            //讲师
            if(roleName.contains("讲师") && !roleName.contains("培训机构")){
                map.put("userId",this.getUserId());
            }
            maps = coursesService.selCourseList(map);
        } else {
            maps = coursesService.selAllCourseList();
        }
        model.addAttribute("courses", maps);
        return "jzweb/chapterItemBank/add";
    }

    @GetMapping("/edit/{id}")
    @RequiresPermissions("jzweb:chapterItemBank:edit")
    String edit(@PathVariable("id") Long id, Model model) {
        List<Map> maps;
        //根据当前登录人的机构id，查询到对应机构的课程；如是超级管理员，则不需要机构查询
        String roleName = getRoleNames();
        if (!roleName.contains("超级用户角色")) {
            Map map = new HashMap();
            map.put("orgId", this.getUser().getOrgId());
            //讲师
            if(roleName.contains("讲师") && !roleName.contains("培训机构")){
                map.put("userId",this.getUserId());
            }
            maps = coursesService.selCourseList(map);
        } else {
            maps = coursesService.selAllCourseList();
        }
        model.addAttribute("courses", maps);
        ChapterItemBankDO chapterItemBank = chapterItemBankService.selectById(id);
        model.addAttribute("chapterItemBank", chapterItemBank);
        return "jzweb/chapterItemBank/edit";
    }

    @GetMapping("/info/{id}")
    @RequiresPermissions("jzweb:chapterItemBank:chapterItemBank")
    String info(@PathVariable("id") Long id, Model model) {
        ChapterItemBankDO chapterItemBank = chapterItemBankService.selectById(id);
        if (chapterItemBank != null) {
            if (chapterItemBank.getCoursesId() != null) {
                CoursesDO coursesDO = coursesService.selectById(chapterItemBank.getCoursesId());
                if (coursesDO != null) {
                    chapterItemBank.setCoursesName(coursesDO.getName());
                }
            }
            if (chapterItemBank.getChapterId() != null) {
                ChapterDO chapterDO = chapterService.selectById(chapterItemBank.getChapterId());
                if (chapterDO != null) {
                    chapterItemBank.setChapterName(chapterDO.getName());
                }
            }
            if (chapterItemBank.getCreaterId() != null) {
                UserDO userDO = userService.selectById(chapterItemBank.getCreaterId());
                if (userDO != null) {
                    chapterItemBank.setCreaterName(userDO.getUsername());
                }
            }
            if (chapterItemBank.getUpdaterId() != null) {
                UserDO userDO = userService.selectById(chapterItemBank.getUpdaterId());
                if (userDO != null) {
                    chapterItemBank.setUpdaterName(userDO.getUsername());
                }
            }
        }
        model.addAttribute("chapterItemBankDO", chapterItemBank);
        return "jzweb/chapterItemBank/info";
    }

    @Log("添加章节题库表")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("jzweb:chapterItemBank:add")
    public Result<String> save(ChapterItemBankDO chapterItemBank) {
        //根据题目内容、课程id、章节id、题目类型判断是否重复
        ChapterItemBankDO chapterItemBankDO = chapterItemBankService
                .findOneByKv("contents", chapterItemBank.getContents(), "courses_id", chapterItemBank.getCoursesId(),
                        "chapter_id", chapterItemBank.getChapterId(), "topic_types", chapterItemBank.getTopicTypes(), "type", chapterItemBank.getType());
        if (chapterItemBankDO != null) {
            return Result.fail("题目已存在，请检查");
        } else {
            Long idd = ibankId(0L, chapterItemBank.getCoursesId(), chapterItemBank.getContents(), chapterItemBank.getOptions(),
                    chapterItemBank.getRightKey(), chapterItemBank.getTopicAnalysis(), chapterItemBank.getTopicTypes());

            chapterItemBank.setIbankId(idd);
            chapterItemBank.setCreaterId(this.getUserId());
            chapterItemBank.setUpdaterId(this.getUserId());
            boolean cb = chapterItemBankService.insert(chapterItemBank);
            if (cb) {
                return Result.ok();
            } else {
                return Result.fail();
            }
        }
    }

    @Log("修改章节题库表")
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("jzweb:chapterItemBank:edit")
    public Result<String> update(ChapterItemBankDO chapterItemBank) {
        //根据题目内容、课程id、章节id、题目类型判断是否重复
        List<ChapterItemBankDO> chapterItemBankDOs = chapterItemBankService
                .findByKv("contents", chapterItemBank.getContents(), "courses_id", chapterItemBank.getCoursesId(),
                        "chapter_id", chapterItemBank.getChapterId(), "topic_types", chapterItemBank.getTopicTypes(), "type", chapterItemBank.getType());
        if (chapterItemBankDOs != null && chapterItemBankDOs.size() > 0) {
            if (chapterItemBankDOs.size() == 1) {
                if (chapterItemBankDOs.get(0).getId().equals(chapterItemBank.getId())) {
                    Long idd = ibankId(chapterItemBankDOs.get(0).getIbankId(), chapterItemBank.getCoursesId(), chapterItemBank.getContents(), chapterItemBank.getOptions(),
                            chapterItemBank.getRightKey(), chapterItemBank.getTopicAnalysis(), chapterItemBank.getTopicTypes());

                    chapterItemBank.setIbankId(idd);
                    chapterItemBank.setUpdaterId(this.getUserId());
                    boolean update = chapterItemBankService.updateById(chapterItemBank);
                    if (update) {
                        return Result.ok();
                    } else {
                        return Result.fail();
                    }
                }
            }
            return Result.fail("题目已存在，请检查");
        } else {
            ChapterItemBankDO chapterItemBankDO = chapterItemBankService.selectById(chapterItemBank.getId());
            Long idd = ibankId(chapterItemBankDO.getIbankId(), chapterItemBank.getCoursesId(), chapterItemBank.getContents(), chapterItemBank.getOptions(),
                    chapterItemBank.getRightKey(), chapterItemBank.getTopicAnalysis(), chapterItemBank.getTopicTypes());

            chapterItemBank.setIbankId(idd);
            chapterItemBank.setUpdaterId(this.getUserId());
            boolean update = chapterItemBankService.updateById(chapterItemBank);
            if (update) {
                return Result.ok();
            } else {
                return Result.fail();
            }
        }
    }

    Long ibankId(Long ibankId, Long coursesId, String contents, String options, String rightKey, String topicAnalysis, Integer type) {
        Long id = null;
        CoursesDO coursesDO = coursesService.selectById(coursesId);
        KnowledgePointsDO knowledgePointsDO = knowledgePointsService.findOneByKv("name", "综合知识点", "pid", 0, "profile_id", coursesDO.getProfileId());
        if (ibankId != 0L) {
            ItemBankDO itemBankDO2 = itemBankService.selectById(ibankId);
            itemBankDO2.setKpointsId(knowledgePointsDO.getId());//知识点id
            itemBankDO2.setProfileId(coursesDO.getProfileId());//证书id
            itemBankDO2.setTopicContent(contents);//题目内容
            itemBankDO2.setOptions(options);//答案选项
            itemBankDO2.setRightKey(rightKey);//正确答案
            itemBankDO2.setTopicAnalysis(topicAnalysis);//题目解析
            itemBankDO2.setCreaterId(this.getUserId());//创建人
            itemBankDO2.setUpdaterId(this.getUserId());//修改人
            itemBankDO2.setCheckerId(this.getUserId());//审核人
            itemBankDO2.setCheckerDate(new Date());//审核时间
            itemBankDO2.setState(1);//默认审核通过
            itemBankDO2.setItemBankType(0);//题库类型（0练习题，1考试题）
            itemBankDO2.setTopicTypes(type);//题目类型（0单选，1多选，2判断，3实操）
            itemBankDO2.setType(0);//类型（0理论，1技能）
            boolean bbc = itemBankService.updateById(itemBankDO2);
            if (bbc) {
                id = ibankId;
            }
        } else {
            ItemBankDO itemBankDO = new ItemBankDO();
            itemBankDO.setKpointsId(knowledgePointsDO.getId());//知识点id
            itemBankDO.setProfileId(coursesDO.getProfileId());//证书id
            itemBankDO.setTopicContent(contents);//题目内容
            itemBankDO.setOptions(options);//答案选项
            itemBankDO.setRightKey(rightKey);//正确答案
            itemBankDO.setTopicAnalysis(topicAnalysis);//题目解析
            itemBankDO.setCreaterId(this.getUserId());//创建人
            itemBankDO.setUpdaterId(this.getUserId());//修改人
            itemBankDO.setCheckerId(this.getUserId());//审核人
            itemBankDO.setCheckerDate(new Date());//审核时间
            itemBankDO.setState(1);//默认审核通过
            itemBankDO.setItemBankType(0);//题库类型（0练习题，1考试题）
            itemBankDO.setTopicTypes(type);//题目类型（0单选，1多选，2判断，3实操）
            itemBankDO.setType(0);//类型（0理论，1技能）
            boolean bbc = itemBankService.insert(itemBankDO);
            if (bbc) {
                id = itemBankDO.getId();
            }
        }

        return id;
    }

    boolean dataList(int ttr, Long coursesId, Long chapterId, String contents, String options, String rightKey, String topicAnalysis, Integer type, Integer score, Long cibackId) {
        boolean b = true;
        if (ttr == 1) {//新增
            //查询是否有对应的章节试卷
            TrainingPapersDO trainingPapersDO = trainingPapersService
                    .findOneByKv("courses_id", coursesId, "chapter_id", chapterId, "type", 0);
            if (trainingPapersDO != null) {
                TrainingQuestionsDO trainingQuestionsDO = trainingQuestionsService
                        .findOneByKv("tpapers_id", trainingPapersDO.getId(), "cibank_id", cibackId, "state", 0);
                if (trainingQuestionsDO == null) {
                    TrainingQuestionsDO trainingQuestionsDO1 = new TrainingQuestionsDO();
                    trainingQuestionsDO1.setIntroduce(contents);//题目内容
                    trainingQuestionsDO1.setTpapersId(trainingPapersDO.getId());//试卷id
                    trainingQuestionsDO1.setOptions(options);//题目选项
                    trainingQuestionsDO1.setRightKey(rightKey);//正确答案
                    trainingQuestionsDO1.setScore(score);//分值
                    trainingQuestionsDO1.setState(0);//默认正常
                    trainingQuestionsDO1.setType(type);//题目类型（0单选，1多选，2判断）
                    trainingQuestionsDO1.setTopicAnalysis(topicAnalysis);//题目解析
                    trainingQuestionsDO1.setCibankId(cibackId);//章节题目id

                    List<TrainingQuestionsDO> trainingQuestionsDOS = trainingQuestionsService.findByKv();
                    if (trainingQuestionsDOS != null) {
                        trainingQuestionsDO1.setTitleNumber(trainingQuestionsDOS.size() + 1);//题号
                    } else {
                        trainingQuestionsDO1.setTitleNumber(1);//题号
                    }

                    boolean ttc = trainingQuestionsService.insert(trainingQuestionsDO1);
                    if (!ttc) {
                        b = false;
                    }
                }
            }
        } else {//编辑
            //查询是否有对应的章节试卷
            TrainingPapersDO trainingPapersDO = trainingPapersService
                    .findOneByKv("courses_id", coursesId, "chapter_id", chapterId);
            if (trainingPapersDO != null) {
                TrainingQuestionsDO trainingQuestionsDO = trainingQuestionsService
                        .findOneByKv("tpapers_id", trainingPapersDO.getId(), "cibank_id", cibackId, "state", 0);
                if (trainingQuestionsDO == null) {
                    TrainingQuestionsDO trainingQuestionsDO1 = new TrainingQuestionsDO();
                    trainingQuestionsDO1.setIntroduce(contents);//题目内容
                    trainingQuestionsDO1.setTpapersId(trainingPapersDO.getId());//试卷id
                    trainingQuestionsDO1.setOptions(options);//题目选项
                    trainingQuestionsDO1.setRightKey(rightKey);//正确答案
                    trainingQuestionsDO1.setScore(score);//分值
                    trainingQuestionsDO1.setState(0);//默认正常
                    trainingQuestionsDO1.setType(type);//题目类型（0单选，1多选，2判断）
                    trainingQuestionsDO1.setTopicAnalysis(topicAnalysis);//题目解析
                    trainingQuestionsDO1.setCibankId(cibackId);//章节题目id

                    List<TrainingQuestionsDO> trainingQuestionsDOS = trainingQuestionsService.findByKv();
                    if (trainingQuestionsDOS != null) {
                        trainingQuestionsDO1.setTitleNumber(trainingQuestionsDOS.size() + 1);//题号
                    } else {
                        trainingQuestionsDO1.setTitleNumber(1);//题号
                    }

                    boolean ttc = trainingQuestionsService.insert(trainingQuestionsDO1);
                    if (!ttc) {
                        b = false;
                    }
                } else {
                    trainingQuestionsDO.setIntroduce(contents);//题目内容
                    trainingQuestionsDO.setTpapersId(trainingPapersDO.getId());//试卷id
                    trainingQuestionsDO.setOptions(options);//题目选项
                    trainingQuestionsDO.setRightKey(rightKey);//正确答案
                    trainingQuestionsDO.setScore(score);//分值
                    trainingQuestionsDO.setState(0);//默认正常
                    trainingQuestionsDO.setType(type);//题目类型（0单选，1多选，2判断）
                    trainingQuestionsDO.setTopicAnalysis(topicAnalysis);//题目解析

                    boolean ttc = trainingQuestionsService.updateById(trainingQuestionsDO);
                    if (!ttc) {
                        b = false;
                    }
                }
            }
        }
        return b;
    }

    @Log("删除章节题库表")
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("jzweb:chapterItemBank:remove")
    public Result<String> remove(Long id) {
        ChapterItemBankDO chapterItemBankDO = chapterItemBankService.selectById(id);
        //根据题库类型、题目类型、类型、题目内容判断是否存在
        ItemBankDO itemBankDO1 = itemBankService.findOneByKv("item_bank_type", 0, "topic_types", chapterItemBankDO.getTopicTypes(), "type", 0, "topic_content", chapterItemBankDO.getContents());
        if (itemBankDO1 != null) {
            boolean bbc = itemBankService.deleteById(itemBankDO1.getId());
            if (!bbc) {
                return Result.fail("章节题目未删除，对应题库题目删除失败，请检查后重试！");
            }
        }
        chapterItemBankService.deleteById(id);
        return Result.ok();
    }

    @Log("批量删除章节题库表")
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("jzweb:chapterItemBank:batchRemove")
    public Result<String> remove(@RequestParam("ids[]") Long[] ids) {
        if (ids != null && ids.length > 0) {
            for (int i = 0; i < ids.length; i++) {
                ChapterItemBankDO chapterItemBankDO = chapterItemBankService.selectById(ids[i]);
                //根据题库类型、题目类型、类型、题目内容判断是否存在
                ItemBankDO itemBankDO1 = itemBankService.findOneByKv("item_bank_type", 0, "topic_types", chapterItemBankDO.getTopicTypes(), "type", 0, "topic_content", chapterItemBankDO.getContents());
                if (itemBankDO1 != null) {
                    boolean bbc = itemBankService.deleteById(itemBankDO1.getId());
                    if (!bbc) {
                        return Result.fail("章节题目未删除，对应题库题目删除失败，请检查后重试！");
                    }
                }
            }
        }

        chapterItemBankService.deleteBatchIds(Arrays.asList(ids));
        return Result.ok();
    }


    /**
     * 下载导入模板
     *
     * @param response
     */
    @RequestMapping("/downloadImportTemplate")
    @RequiresPermissions("jzweb:chapterItemBank:import")
    @ResponseBody
    public void downloadImportTemplate(HttpServletResponse response) {
        List<ChapterItemBankVo> list = new LinkedList<>();
        //导出操作
        EasyPoiUtil.exportExcel(list, "章节题库题目信息导入模板", "章节题库题目信息导入模板", ChapterItemBankVo.class, "章节题库题目信息导入模板", response);
    }

    /**
     * 题目信息导入
     *
     * @param file excel文件
     */
    @Log("题目信息导入")
    @PostMapping("/import")
    @ResponseBody
    @Transactional
    @RequiresPermissions("jzweb:chapterItemBank:import")
    public Result<?> importExcel(@RequestParam("file") MultipartFile file, String coursesId, String chapterId) {
        //---------------------------------检测导入信息及条件-----------------------------------------
        //第一步--判断文件格式
        if (!"application/vnd.ms-excel".equals(file.getContentType())) {
            return Result.fail("文件格式错误，请选择.xls文件");
        }

        //第二步--解析文件获得数据
        List<ChapterItemBankVo> list = EasyPoiUtil.importExcel(file, 1, 1, ChapterItemBankVo.class);
        if (list.size() == 0) {
            return Result.fail("Excel数据为空，请完善");
        }

        //---------------------------------验证数据并导入-----------------------------------------
        //数据该表第三行，第一行标题，第二行表头
        int startRow = 3;
        int cout = 1;//错误信息计数
        List<ChapterItemBankDO> bankDOList = new ArrayList<>();
        List<ErrorCodeVo> list1 = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            StringBuilder sb = new StringBuilder();
            //第一步验证是否存在空值
            if (StringUtils.isBlank(list.get(i).getType())) {
                sb.append("第" + (i + startRow) + "行类型未填写，请完善！" + ";");
            } else {
                if (StringUtils.isBlank(list.get(i).getTopicTypes())) {
                    sb.append("第" + (i + startRow) + "行题目类型未填写，请完善！" + ";");
                } else {
                    if (StringUtils.isBlank(list.get(i).getTopicContent())) {
                        sb.append("第" + (i + startRow) + "行题目内容未填写，请完善！" + ";");
                    } else {
                        if (StringUtils.isBlank(list.get(i).getOptions())) {
                            sb.append("第" + (i + startRow) + "行答案选项未填写，请完善！" + ";");
                        } else {
                            if (StringUtils.isBlank(list.get(i).getRightKey())) {
                                sb.append("第" + (i + startRow) + "行正确答案未填写，请完善！" + ";");
                            } else {
                                if (StringUtils.isBlank(list.get(i).getTopicAnalysis())) {
                                    sb.append("第" + (i + startRow) + "行题目解析未填写，请完善！" + ";");
                                } else {
                                    if (StringUtils.isBlank(list.get(i).getScore())) {
                                        sb.append("第" + (i + startRow) + "行分值未填写，请完善！" + ";");
                                    } else {
                                        if (!IdCardUtil.isNumeric(list.get(i).getScore())) {
                                            sb.append("第" + (i + startRow) + "行分值不是数字，请修改！" + ";");
                                        } else {
                                            //第四步排重验证（自身比较）
                                            for (int j = 0; j < list.size(); j++) {
                                                if (i != j) {
                                                    if (list.get(i).getTopicContent().equals(list.get(j).getTopicContent())) {
                                                        sb.append("第" + (i + startRow) + "行跟第" + (j + startRow) + "行题目内容重复，重复值：" + list.get(i).getTopicContent() + ";");
                                                    }
                                                }
                                            }

                                            int topicType = 9;
                                            int type = 9;

                                            //题目类型（0单选，1多选，2判断）
                                            if (list.get(i).getTopicTypes().equals("单选")) {
                                                topicType = 0;
                                            } else if (list.get(i).getTopicTypes().equals("多选")) {
                                                topicType = 1;
                                            } else if (list.get(i).getTopicTypes().equals("判断")) {
                                                topicType = 2;
                                            } else {
                                                sb.append("第" + (i + startRow) + "行题目类型填写错误，请按照示例填写！" + ";");
                                            }

                                            //类型（0练习，1测试）
                                            if (list.get(i).getType().equals("练习")) {
                                                type = 0;
                                            } else if (list.get(i).getType().equals("测试")) {
                                                type = 1;
                                            } else {
                                                sb.append("第" + (i + startRow) + "行类型填写错误，请按照示例填写！" + ";");
                                            }

                                            if (topicType != 9 && type != 9) {
                                                //第六步排重验证（和数据库比较），根据题目内容、课程id、章节id、题目类型判断
                                                ChapterItemBankDO chapterItemBankDO = chapterItemBankService
                                                        .findOneByKv("contents", list.get(i).getTopicContent(), "courses_id", Long.parseLong(coursesId),
                                                                "chapter_id", Long.parseLong(chapterId), "topic_types", topicType, "type", type);
                                                if (chapterItemBankDO != null) {
                                                    sb.append("第" + (i + startRow) + "行题目已存在，请检查！" + ";");
                                                } else {
                                                    CoursesDO coursesDO = coursesService.selectById(Long.parseLong(coursesId));
                                                    KnowledgePointsDO knowledgePointsDO = knowledgePointsService.findOneByKv("name", "综合知识点", "pid", 0, "profile_id", coursesDO.getProfileId());
                                                    ItemBankDO itemBankDO1 = new ItemBankDO();
                                                    itemBankDO1.setKpointsId(knowledgePointsDO.getId());//知识点id
                                                    itemBankDO1.setProfileId(coursesDO.getProfileId());//证书id
                                                    itemBankDO1.setTopicContent(list.get(i).getTopicContent());//题目内容
                                                    itemBankDO1.setOptions(list.get(i).getOptions());//答案选项
                                                    itemBankDO1.setRightKey(list.get(i).getRightKey());//正确答案
                                                    itemBankDO1.setTopicAnalysis(list.get(i).getTopicAnalysis());//题目解析
                                                    itemBankDO1.setCreaterId(this.getUserId());//创建人
                                                    itemBankDO1.setUpdaterId(this.getUserId());//修改人
                                                    itemBankDO1.setCheckerId(this.getUserId());//审核人
                                                    itemBankDO1.setCheckerDate(new Date());//审核时间
                                                    itemBankDO1.setState(1);//默认审核通过
                                                    itemBankDO1.setItemBankType(0);//题库类型（0练习题，1考试题）
                                                    itemBankDO1.setTopicTypes(topicType);//题目类型（0单选，1多选，2判断，3实操）
                                                    itemBankDO1.setType(0);//类型（0理论，1技能）
                                                    boolean bbc = itemBankService.insert(itemBankDO1);
                                                    if (bbc) {
                                                        //加入章节题目信息
                                                        ChapterItemBankDO chapterItemBankDO1 = new ChapterItemBankDO();
                                                        chapterItemBankDO1.setCoursesId(Long.parseLong(coursesId));//课程id
                                                        chapterItemBankDO1.setChapterId(Long.parseLong(chapterId));//章节id
                                                        chapterItemBankDO1.setIbankId(itemBankDO1.getId());//题库id
                                                        chapterItemBankDO1.setTopicTypes(topicType);//题目类型（0单选，1多选，2判断）
                                                        chapterItemBankDO1.setType(type);//类型（0练习，1测试）
                                                        chapterItemBankDO1.setContents(list.get(i).getTopicContent());//题目内容
                                                        chapterItemBankDO1.setOptions(list.get(i).getOptions());//答案选项
                                                        chapterItemBankDO1.setRightKey(list.get(i).getRightKey());//正确答案
                                                        chapterItemBankDO1.setTopicAnalysis(list.get(i).getTopicAnalysis());//题目解析
                                                        chapterItemBankDO1.setScore(Integer.parseInt(list.get(i).getScore()));//分值
                                                        chapterItemBankDO1.setState(0);//默认正常
                                                        chapterItemBankDO1.setCreaterId(this.getUserId());//创建人
                                                        chapterItemBankDO1.setUpdaterId(this.getUserId());//修改人
                                                        bankDOList.add(chapterItemBankDO1);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }


            if (sb.length() > 0) {
                ErrorCodeVo errorCodeVo = new ErrorCodeVo();
                errorCodeVo.setSeq(cout);
                cout += 1;
                errorCodeVo.setErrorCode(sb.toString());
                list1.add(errorCodeVo);
            }
        }

        if (list1.size() == 0) {
            boolean c = chapterItemBankService.insertBatch(bankDOList, bankDOList.size());
            if (c) {
                return Result.ok("成功导入" + list.size() + "条数据");
            } else {
                return Result.fail("题目信息导入错误，请稍后重试或联系管理员");
            }
        } else {
            JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(list1));
            //将list1存到缓存中
            EhCacheUtil.put("chapterItemBank" + this.getUserId(), jsonArray);
            return Result.build(EnumErrorCode.FileImportError.getCode(), EnumErrorCode.FileImportError.getMsg());
        }
    }

    /**
     * 导出错误信息
     *
     * @param request
     * @param response
     * @throws Exception
     * @author kl
     */
    @Log("导出错误信息")
    @GetMapping("/importError")
    @ResponseBody
    @Transactional
    @RequiresPermissions("jzweb:chapterItemBank:import")
    public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/vnd.ms-excel");
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("章节题库题目导入错误信息", "UTF-8") + ".xls");
        //编码
        response.setCharacterEncoding("UTF-8");
        String jsonArray = EhCacheUtil.get("chapterItemBank" + this.getUserId()).toString();
        JSONArray arrayList = JSONArray.parseArray(jsonArray);
        //转换为目标对象list
        List<ErroeDownVo> groupList = JSONObject.parseArray(arrayList.toJSONString(), ErroeDownVo.class);
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), ErroeDownVo.class, groupList);
        workbook.write(response.getOutputStream());
    }

}
